<template>
  <div class="h-full w-full p-5">
    <div class="card-box h-full">
      <div class="user-list-container min-h-full">
        <!-- 页面标题和操作区 -->
        <div class="page-header">
          <h1 class="page-title">用户管理</h1>
        </div>

        <!-- 筛选区 -->
        <el-card class="filter-card">
          <div class="filter-group">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户手机号"
              clearable
              class="search-input"
              @keyup.enter="handleSearch"
              @clear="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <IconifyIcon icon="material-symbols:search" />
                </el-button>
              </template>
            </el-input>
          </div>
        </el-card>

        <!-- 用户列表 -->
        <el-card class="table-card">
          <el-table
            :data="tableData"
            border
            stripe
            :loading="tableLoading"
            empty-text="暂无用户数据"
            style="width: 100%"
          >
            <!-- 表格列定义省略 -->
            <el-table-column
              type="index"
              label="序号"
              width="80"
              align="center"
            ></el-table-column>
            <el-table-column label="用户头像" align="center">
              <template #default="scope">
                <img
                  :src="scope.row.avatarUrl"
                  alt="用户图片"
                  v-if="scope.row.avatarUrl"
                  style="
                    width: 60px;
                    height: 60px;
                    object-fit: cover;
                    border-radius: 4px;
                  "
                />
                <span v-else>暂无用户头像</span>
              </template>
            </el-table-column>
            <el-table-column prop="nickName" label="用户昵称" align="center" />
            <el-table-column prop="phone" label="用户手机号" align="center" />
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
            />
            <el-table-column label="角色" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.isAdmin === 0 ? 'success' : 'info'">
                  {{ scope.row.isAdmin === 0 ? '管理员' : '普通用户' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template #default="scope">
                <el-button type="primary" @click="handleGoto(scope.row)"
                  >编辑</el-button
                >
                <el-popconfirm
                  :title="`确定要${scope.row.isAdmin === 0 ? '取消' : '设置'}该用户为${scope.row.isAdmin === 0 ? '普通用户' : '管理员'}吗？`"
                  @confirm="handleSetAdmin(scope.row)"
                >
                  <template #reference>
                    <el-button
                      :type="scope.row.isAdmin === 0 ? 'warning' : 'success'"
                    >
                      {{
                        scope.row.isAdmin === 0 ? '取消管理员' : '设为管理员'
                      }}
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totaluser"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
  ElButton,
  ElCard,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElMessage,
  ElPopconfirm,
  ElTag,
} from 'element-plus';
import { IconifyIcon } from '@vben/icons';
import { getUserList, setUserRole, type userApi } from '#/api/user';

const router = useRouter();

// 状态管理
const searchKeyword = ref('');
const tableLoading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const totaluser = ref(0);
const tableData = ref<userApi.listItem[]>([]);

// 监听pageSize变化，重置currentPage为1并重新加载数据
watch(pageSize, (newSize) => {
  currentPage.value = 1; // 页码重置为1
});

// 监听currentPage变化，重新加载数据
watch(currentPage, (newPage) => {
  loaduser();
});

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置页码
  loaduser();
};

const handleGoto = (row?: userApi.listItem | undefined) => {
  if (row && row.id) {
    router.push(`/product/listDetail/${row.id}`);
  } else {
    router.push('/product/listDetail');
  }
};

// 设置用户角色为管理员
const handleSetAdmin = async (row: userApi.listItem) => {
  try {
    const data = await setUserRole({
      id: row.id,
    });

    if (data.code === 200) {
      ElMessage.success(`${row.isAdmin === 0 ? '取消' : '设置'}管理员成功`);
      loaduser();
    } else {
      ElMessage.error(
        `${row.isAdmin === 0 ? '取消' : '设置'}管理员失败：` +
          (data.message || '未知错误'),
      );
    }
  } catch (error) {
    console.error('设置管理员失败:', error);
    ElMessage.error(`${row.isAdmin === 0 ? '取消' : '设置'}管理员失败`);
  }
};

// 加载用户数据
const loaduser = async () => {
  tableLoading.value = true;
  try {
    const {
      data: { list, total },
    } = await getUserList({
      phone: searchKeyword.value,
      pageNum: currentPage.value, // 传递当前页码
      pageSize: pageSize.value, // 传递每页条数
    });
    totaluser.value = Number(total);
    tableData.value = list;
  } catch (error) {
    console.error('加载用户失败:', error);
    tableData.value = [];
    totaluser.value = 0;
    ElMessage.error('加载用户数据失败');
  } finally {
    tableLoading.value = false;
  }
};
// 页面加载时获取数据
loaduser();
</script>

<style scoped lang="scss">
.user-list-container {
  padding: 20px;
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }
  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }

  .filter-card {
    margin-bottom: 20px;
    .filter-group {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: center;
      .search-input {
        width: 300px;
      }
    }
  }
}
</style>
